package com.sinodata.ns.mc;

import com.sinodata.ns.cell.CellBDInfo;
import com.sinodata.ns.cell.JLBDInfo;
import com.sinodata.ns.cell.JLBDManager;
import com.sinodata.ns.sv.ISupervisor;
import com.sinodata.ns.sv.SupervisorManager;

import jt.classic.system.ISystem;
import jt.classic.system.SimpleAction;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.user.IUser;

import net.sf.json.JSONArray;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.limp.basework.impl.CommonBean4HSQ;

import org.limp.mine.DataTrimmerI;
import org.limp.mine.DateTrimmer;

import java.sql.Connection;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 监理监控action
 *
 * @author mido
 *
 */
public class MCAction extends SimpleAction {
    /**
    * 监理标段
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws Exception
    */
    public ActionForward list(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        StringBuffer where = new StringBuffer(" WHERE SVBD_GROUPID = '" +
                ((user.igroup() != null) ? user.igroup().id() : "0") + "' ");

        String sql = "SELECT APP_NS_SVBD.ID,APP_NS_SVBD.SVBD_NAME FROM APP_NS_SVBD " + where.toString() +
            " ORDER BY SVBD_NAME";

        if (ISystem.matchrole(user, "NSManager")) {
            String purviewSql = ObjectManager.getObjectPurviewSQL("cell", user,
                    0, null);

            where = new StringBuffer(
                    " WHERE APP_NS_SVBD.ID = APP_NS_SVBDITEM.ID AND APP_NS_SVBDITEM.CB_ID IN (" +
                    purviewSql + " GROUP BY OBJ_ID,OBJ_NAME)");

            sql = "SELECT APP_NS_SVBD.ID,APP_NS_SVBD.SVBD_NAME FROM APP_NS_SVBD,APP_NS_SVBDITEM " +
                where.toString() + " GROUP BY APP_NS_SVBD.ID,APP_NS_SVBD.SVBD_NAME ORDER BY SVBD_NAME";
        }

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmerI trimmer = new DataTrimmerI(conn);

            //DataItemList dil = trimmer.createDIL();
            List resultList = trimmer.searchMultiData(sql, null);

            if ((resultList != null) && !resultList.isEmpty()) {
                JLBDManager jm = new JLBDManager(conn);

                SupervisorManager sm = new SupervisorManager(conn);

                for (int i = 0; i < resultList.size(); i++) {
                    Map map = (Map) resultList.get(i);
                    String id = (String) map.get("ID");

                    /*标段信息*/
                    JLBDInfo info = jm.getJLBDInfoById(id);

                    map.put("SVBD_ID", info.id());
                    map.put("SVBD_GROUPID",
                        (info.igroup() != null) ? info.igroup().id() : "");
                    map.put("SVBD_GROUP",
                        (info.igroup() != null) ? info.igroup().iname() : "");
                    map.put("C_NAME",
                        ((info.icell() != null) ? info.icell().iname() : ""));
                    map.put("C_UNIT",
                        ((info.icell() != null) ? info.icell().iunit() : ""));
                    map.put("C_TYPE",
                        ((info.icell() != null) ? info.icell().itype() : ""));
                    map.put("C_AREA",
                        ((info.icell() != null) ? info.icell().iarea() : ""));
                    map.put("C_LON",
                        ((info.icell() != null) ? info.icell().ilon() : ""));
                    map.put("C_LAT",
                        ((info.icell() != null) ? info.icell().ilat() : ""));

                    List list = info.icell().ibd();

                    if ((list != null) && !list.isEmpty()) {
                        for (int j = 0; j < list.size(); j++) {
                            CellBDInfo cbi = (CellBDInfo) list.get(j);

                            Map cbMap = new HashMap();

                            cbMap.put("CB_ID", cbi.id());
                            cbMap.put("CB_NAME", cbi.iname());
                            cbMap.put("CB_LON", cbi.ilon());
                            cbMap.put("CB_LAT", cbi.ilat());

                            list.set(j, cbMap);
                        }
                    }

                    map.put("CBLIST", list);

                    /*监理人员信息*/
                    List svList = sm.getSupervisorsByJLBD(id);

                    if ((svList != null) && !svList.isEmpty()) {
                        for (int j = 0; j < svList.size(); j++) {
                            ISupervisor sv = (ISupervisor) svList.get(j);

                            List kqList = sm.getKaoqinInfoBySupervisor(sv.iuser()
                                                                         .id(),
                                    DateTrimmer.getYMD(), -1);

                            List trackList = sm.getTrackInfoBySupervisor(sv.iuser()
                                                                           .id(),
                                    DateTrimmer.getYMD());

                            Map svMap = new HashMap();

                            svMap.put("SV_ID", sv.id());
                            svMap.put("SV_NAME", sv.iname());
                            svMap.put("SV_MOBILE", sv.iuser().iphone());
                            svMap.put("SV_SEX", sv.iuser().isex());
                            svMap.put("SV_JOB", sv.iuser().ijob());
                            svMap.put("SV_BD",
                                ((sv.icellbd() != null) ? sv.icellbd().iname()
                                                        : ""));
                            svMap.put("KQLIST", kqList);
                            svMap.put("TKLIST", trackList);

                            svList.set(j, svMap);
                        }
                    }

                    map.put("SVLIST", svList);
                }
            }

            JSONArray jsonArray = JSONArray.fromObject(resultList);

            String jsonString = "{success: true, \"queryList\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false}");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }

    /**
     * 监控信息刷新
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward refresh(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String ids = (String) param.get("ids");

        StringBuffer where = new StringBuffer(" WHERE ID IN (" + ids + ") ");

        String sql = "SELECT * FROM APP_NS_SVBD " + where.toString() +
            " ORDER BY SVBD_NAME";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmerI trimmer = new DataTrimmerI(conn);

            //DataItemList dil = trimmer.createDIL();
            List resultList = trimmer.searchMultiData(sql, null);

            if ((resultList != null) && !resultList.isEmpty()) {
                JLBDManager jm = new JLBDManager(conn);

                SupervisorManager sm = new SupervisorManager(conn);

                for (int i = 0; i < resultList.size(); i++) {
                    Map map = (Map) resultList.get(i);
                    String id = (String) map.get("ID");

                    /*标段信息*/
                    JLBDInfo info = jm.getJLBDInfoById(id);

                    map.put("SVBD_ID", info.id());
                    map.put("SVBD_GROUPID",
                        (info.igroup() != null) ? info.igroup().id() : "");
                    map.put("SVBD_GROUP",
                        (info.igroup() != null) ? info.igroup().iname() : "");
                    map.put("C_NAME",
                        ((info.icell() != null) ? info.icell().iname() : ""));
                    map.put("C_UNIT",
                        ((info.icell() != null) ? info.icell().iunit() : ""));
                    map.put("C_TYPE",
                        ((info.icell() != null) ? info.icell().itype() : ""));
                    map.put("C_AREA",
                        ((info.icell() != null) ? info.icell().iarea() : ""));
                    map.put("C_LON",
                        ((info.icell() != null) ? info.icell().ilon() : ""));
                    map.put("C_LAT",
                        ((info.icell() != null) ? info.icell().ilat() : ""));

                    List list = info.icell().ibd();

                    if ((list != null) && !list.isEmpty()) {
                        for (int j = 0; j < list.size(); j++) {
                            CellBDInfo cbi = (CellBDInfo) list.get(j);

                            Map cbMap = new HashMap();

                            cbMap.put("CB_ID", cbi.id());
                            cbMap.put("CB_NAME", cbi.iname());
                            cbMap.put("CB_LON", cbi.ilon());
                            cbMap.put("CB_LAT", cbi.ilat());

                            list.set(j, cbMap);
                        }
                    }

                    map.put("CBLIST", list);

                    /*监理人员信息*/
                    List svList = sm.getSupervisorsByJLBD(id);

                    if ((svList != null) && !svList.isEmpty()) {
                        for (int j = 0; j < svList.size(); j++) {
                            ISupervisor sv = (ISupervisor) svList.get(j);

                            List kqList = sm.getKaoqinInfoBySupervisor(sv.iuser()
                                                                         .id(),
                                    DateTrimmer.getYMD(), -1);

                            List trackList = sm.getTrackInfoBySupervisor(sv.iuser()
                                                                           .id(),
                                    DateTrimmer.getYMD());

                            Map svMap = new HashMap();

                            svMap.put("SV_ID", sv.id());
                            svMap.put("SV_NAME", sv.iname());
                            svMap.put("SV_MOBILE", sv.iuser().iphone());
                            svMap.put("SV_SEX", sv.iuser().isex());
                            svMap.put("SV_JOB", sv.iuser().ijob());
                            svMap.put("SV_BD",
                                ((sv.icellbd() != null) ? sv.icellbd().iname()
                                                        : ""));
                            svMap.put("KQLIST", kqList);
                            svMap.put("TKLIST", trackList);

                            svList.set(j, svMap);
                        }
                    }

                    map.put("SVLIST", svList);
                }
            }

            JSONArray jsonArray = JSONArray.fromObject(resultList);

            String jsonString = "{success: true, \"queryList\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false}");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }
}
